package com.gm.blog.controller;

import com.gm.blog.enums.ResultEnum;
import com.gm.blog.pojo.Blog;
import com.gm.blog.service.BlogService;
import com.gm.blog.utils.IdWorker;
import com.gm.blog.utils.Page;
import com.gm.blog.utils.Result;
import com.gm.blog.utils.StringUtils;
import com.gm.blog.vo.BlogVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/blog")
public class BlogController {
    @Autowired
    private BlogService blogService;

    @Autowired
    private IdWorker idWorker;
    /**
     * 添加博客信息
     */
    @RequestMapping(value="/save",method = RequestMethod.POST)
    public Result<Object> save(@RequestBody Blog blog){
        if(blog==null){
            return new Result<>(ResultEnum.ERROR);
        }else{
            blog.setBlogId(idWorker.nextId()+"");
            blogService.save(blog);
            return new Result<>("添加博客成功");
        }
    }
    /**
     * 修改博客信息
     */
    @RequestMapping(value = "/update",method = RequestMethod.POST)
    public Result<Object> update(@RequestBody Blog blog){
        blogService.update(blog);
        return new Result<>("博客信息修改成功");
    }

    /**
     * 阅读博客内容
     */
    @RequestMapping(value="/read/{id}",method = RequestMethod.GET)
    public Result<Object> read(@PathVariable Integer id){
        BlogVo byId = blogService.readById(id);
        return new Result<>(byId);
    }
    /**
     * 删除博客内容
     */
    @RequestMapping(value="delete/{id}",method = RequestMethod.DELETE)
    public Result<Object> delete(@PathVariable Integer id){
        blogService.delete(id);
        return new Result<>("删除成功");
    }
    /**
     * 分页
     */
    @RequestMapping(value = "/getByPage", method = RequestMethod.POST)
    public Result<Page<BlogVo>> getByPage(@RequestBody Page<BlogVo> page) {
        String sortColumn = page.getSortColumn();
        if (StringUtils.isNotBlank(sortColumn)) {
            // 排序列不为空
            String[] sortColumns = {"blog_goods", "blog_read", "blog_collection",
                    "type_name", "blog_comment", "created_time", "update_time"};
            List<String> sortList = Arrays.asList(sortColumns);
            if (!sortList.contains(sortColumn.toLowerCase())) {
                return new Result<>(ResultEnum.PARAMS_ERROR.getCode(), "排序参数不合法！");
            }
        }
        page = blogService.getByPage(page);
        return new Result<>(page);
    }
}
